package com.ln.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ln.yygh.hosp.repository.ScheduleRepository;
import com.ln.yygh.hosp.service.*;
import com.ln.yygh.model.hosp.*;
import com.ln.yygh.vo.hosp.*;
import org.joda.time.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @author: lianXiaoChen
 * @create: 2021-05-31 18:46
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private Hospitalervice hospitalervice;
    @Autowired
    private DepartmentService departmentService;

    @Override//添加
    public void saveSchedule(Map<String, Object> paramMap) {
        //查询数据库中是否存在
        String json = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(json, Schedule.class);
        /**
         * 保存和修改是一起的
         * 需要我们进行判断，要是有就是修改，没有就是新增
         * 医院编码是唯一的，使用这个试题里面的医院的编码去数据库查询，看看有没有信息
         *
         */
        if (schedule != null) {

            Schedule sd = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
            /**
             * 有的话，走修改，么有的话就是新增
             */
            if (sd == null) {
                schedule.setUpdateTime(new Date());
                schedule.setIsDeleted(0);
                schedule.setStatus(1);
                scheduleRepository.save(schedule);
            } else {
                //修改 人添加id
                schedule.setCreateTime(new Date());
                schedule.setUpdateTime(new Date());
                schedule.setIsDeleted(0);
                schedule.setStatus(1);
                scheduleRepository.save(schedule);
            }
        }

    }

    @Override//列表+分页
    public Page<Schedule> getSchedule(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(page - 1, limit, sort);
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);
        //加载查询条件
        ExampleMatcher matching = ExampleMatcher.matching()//构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符
                .withIgnoreCase(true);//忽略大小写
        //创建实列
        Example<Schedule> example = Example.of(schedule, matching);
        return scheduleRepository.findAll(example, pageable);
    }

    @Override//删除
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        //判断此对象是否为空
        if (null != schedule) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    @Override//根据医院编号和科室编号进行查询排班规则信息
    public Map<String, Object> getRuleSchedule(Integer page, Integer limit, String hoscode, String depcode) {
        //根据医院编号和科室查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);//使用Criteria进行条件分装
        //根据工作日进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")//分组字段
                .first("workDate").as("workDate")
               //统计号源
                .count().as("docCount")
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                //实现分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        //调用方法最总执行
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> mappedResults = aggResults.getMappedResults();
        //分组查询后总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalaggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalaggResults.getMappedResults().size();
        //获取日期对应星期
        for (BookingScheduleRuleVo mappedResult : mappedResults) {
            Date workDate = mappedResult.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            mappedResult.setDayOfWeek(dayOfWeek);
        }
        //设置最终信息 并且返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList",mappedResults);
        result.put("total",total);

        //获取医院名称
        String hosName = hospitalervice.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);
        result.put("baseMap",baseMap);

        return result;
    }

    @Override//根据医院编号科室编号工作日期查询
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        List<Schedule> scheduleList =//根据参数查询mongodb
                scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());
        //吧list集合便利设置其他值
        scheduleList.stream().forEach(item ->{
            this.packageSchedule(item);
        });
        return scheduleList;
    }
    //封装排班详情 编号工作日期查询
    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalervice.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    //日期转换星期
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

}
